/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */

/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var detectCycle = function(head) {
    if(!head){
        return null;
    }
    let first=head,second=head;
    while(true){
        if(first==null || first.next==null){
            return null;
        }
        first=first.next.next;
        second=second.next;
        if(first==second){
            break;
        }
    }
    first=head;
    while(first!=second){
        first=first.next;
        second=second.next;
    }
    return first;
};
/*  var detectCycle = function(head) {
    let set = new Set();
    while(head!=null){
        if(set.has(head)){
            return head;
        }
        else{
            set.add(head);
        }
        head=head.next;
    }
    return null;  
}; */